package com.example.spring5.designmode.strategy;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: Hu Rui
 * @Date: 2021/11/12 11:16
 */
@Component
public class ConnectHelper implements ApplicationContextAware {
    private Map<StrategyEnum, ConnectStrategy> beansCache = new HashMap<>();
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, ConnectStrategy> beansOfType = applicationContext.getBeansOfType(ConnectStrategy.class);
        for (Map.Entry<String, ConnectStrategy> connectStrategyEntry : beansOfType.entrySet()) {
            beansCache.put(connectStrategyEntry.getValue().getStrategyType(), connectStrategyEntry.getValue());
        }
    }

    public void execute(StrategyEnum strategyEnum, String resource) {
        beansCache.get(strategyEnum).processStrategy(resource);
    }
}
